import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class TestScrollControllerPage extends StatefulWidget {
  const TestScrollControllerPage({Key? key}) : super(key: key);

  @override
  _TestScrollControllerPageState createState() =>
      _TestScrollControllerPageState();
}

class _TestScrollControllerPageState extends State<TestScrollControllerPage> {
  final ScrollController _scrollController = ScrollController();
  bool _showToTopBtn = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      final offset = _scrollController.offset;
      print("_scrollController: $offset");
      if (offset < 1000 && _showToTopBtn) {
        setState(() {
          _showToTopBtn = false;
        });
      } else if (offset >= 1000 && !_showToTopBtn) {
        setState(() {
          _showToTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("test scroll controller"),
      ),
      body: Container(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          children: [
            const ListTile(
              title: Text("table header"),
            ),
            Expanded(
              child: Scrollbar(
                child: ListView.builder(
                  controller: _scrollController,
                  itemCount: 300,
                  prototypeItem: const ListTile(
                    title: Text("1"),
                  ),
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      title: Text("$index"),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: !_showToTopBtn
          ? null
          : FloatingActionButton(
              child: const Icon(Icons.arrow_upward),
              onPressed: () {
                _scrollController.animateTo(0,
                    duration: const Duration(microseconds: 200),
                    curve: Curves.ease);
              },
            ),
    );
  }
}
